package com;

import com.user.service.UserAutrorizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.RequestMatcher;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private UserAutrorizeService userAutrorizeService;

    private MyAuthenticationProvider myAuthenticationProvider;

    @Autowired
    public WebSecurityConfig(UserAutrorizeService userAutrorizeService, MyAuthenticationProvider myAuthenticationProvider) {
        this.userAutrorizeService = userAutrorizeService;
        this.myAuthenticationProvider = myAuthenticationProvider;
    }


    /**
     * 匹配 "/" 路径，不需要权限即可访问
     * 匹配 "/user" 及其以下所有路径，都需要 "USER" 权限
     * 登录地址为 "/login"，登录成功默认跳转到页面 "/user"
     * 退出登录的地址为 "/logout"，退出成功后跳转到页面 "/login"
     * 默认启用 CSRF
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义csrf过滤器
        //RequestMatcher csrfSecurityRequestMatcher = new CsrfSecurityRequestMatcher() ;
        //.csrf().requireCsrfProtectionMatcher(csrfSecurityRequestMatcher)
        http.csrf()
                .ignoringAntMatchers("/druid/**")
                .ignoringAntMatchers("/api/**")
                .and()
                .authorizeRequests()
                .antMatchers("/").hasRole("USER")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/api/**").hasRole("ADMIN")
                .and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/success")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login")
                .and();
    }

    /**
     * 在内存中创建一个名为 "admin" 的用户，密码为 "admin"，拥有 "USER,ADMIN" 权限
     */
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder
                .inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER", "ADMIN");
        //builder.authenticationProvider(myAuthenticationProvider);
        builder.userDetailsService(userAutrorizeService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
